//主要脚本文件

var fun_dom_isBodyMouse;    //当前的方法阻止

//主要脚本文件
const main = new Vue({
    el: "#body",
    data: function () 
    {
        return {
            test: "sss ",
            //当前鼠标划过的位置的dom组
            mouse_movePath: [],

            //当前显示的dom

            //当前空格按下是否可以移动body内容   是否拖动模式
            mouse_moveBody:false,
            //当前move移动的xy坐标  !切换model时归位坐标
            canvasThisPosition:{
                x:0,
                y:0
            },
            //记录当前鼠标第一次按下时的位置
            canvasBufferPosition:{
                x:0,
                y:0,
            },
            //记录当前move移动时按下的位置
            canvasThisDownPosition:{
                x:0,
                y:0
            },
            //当前move是否按下
            mouse_isDown:false,
            //window 的宽高
            window:{
                w:0,
                h:0,
            },
            mouse_move_funs:[],
            //当前选择的select模块id
            mouse_selectComponentId:"",
            mouse_selectComponentIdS:[],
            //当前用户是否按下ctrl键
            mouse_selectKeyDown_ctrl:false,
            //当前用户按下时获取当前所选择的内容xy并存入到当前的列表里面
            mouse_selectBufferPosition:[],      
            //链接的data
            linkData:{
                model_server:{},
                model_app:{},
            },

            //当前关联的对象列表的线条
            stringList:[],




            
            // mediaSize:100, 请求的网络数据
            requestData:{
                mediaSize:{data:100},              //当前屏幕缩放
                canvasThisPosition:{
                    x:0,
                    y:0
                },
                projectName:"项目名称",         //当前的项目名称
                projectCode:"1231243214234234", //当前项目的数据库编码
                modelType:'model_server',     //server端  和  app端
                model_server:{},
                model_app:{},
            },




        }
    },
    computed:{
        /**
         * 计算当前的选中的内容的宽高大小以及是否时选中的
         */
        computed_selectComponentID:function()
        {
            let list = [];
            let returnData = {
                isShow:false,
                x:0,
                y:0,
                w:0,
                h:0
            };
            if(!(this.mouse_selectComponentIdS == "" || this.mouse_selectComponentIdS == undefined))
            {
                for (let i = 0; i < this.mouse_selectComponentIdS.length; i++) {
                    const item = this.mouse_selectComponentIdS[i];
                    let thisData 
                    try{
                        thisData  = this.requestData[this.requestData.modelType][item].data;
                    }catch(e)
                    {
                        continue;
                    }
                    
                    let returnData = {
                        isShow:false,
                        x:0,
                        y:0,
                        w:0,
                        h:0
                    };

                    try{
                        returnData.isShow = true;
                        returnData.x = thisData.position.x-5;
                        returnData.y = thisData.position.y-5;
                        returnData.w = thisData.innerSize.width+10;
                        returnData.h = thisData.innerSize.height+10;
    
                    }catch(e)
                    {

                    }
                    list.push(returnData);
                }
                

                

            }
            

            return list;

        },
        /**
         * 计算属性计算当前有多少模块中的关联并且的关系
         */
        //  computed_allLink:function()
        //  {
           


        //     // thisModel.
            
            

        //     return returnData;
        //  },



    },
    methods: {

        /**---------------------------------------------------------
         * window 事件当前的鼠标按下时的动作
         * @param {事件} e 
         */
        eventWin_mouseDown: function (e) 
        {
            // this.eventBody_click(e,true);
            //当前数组里面未选择内容
            if(
                this.mouse_selectComponentIdS.length == 0  || 
                this.mouse_selectComponentIdS[0] == undefined ||
                this.mouse_selectComponentIdS.length == 1 
                )
            {
                let {dom}  = util_parseDomPath({
                    path:e.path,
                    el:".movetrue"
                });

                //如果按着ctrol则不执行当前
                if(!this.mouse_selectKeyDown_ctrl)
                {
                    this.mouse_selectComponentIdS = [];
                }
                this.mouse_selectComponentIdS.push(dom.id);
            }









            

            this.mouse_isDown = true;
            //当前鼠标按下时不可选择内容
            this.$el.style.userSelect = "none";

            //记录当前的xy轴
            // console.log(e.pageX,e.pageY);
            this.canvasBufferPosition.x = e.pageX;
            this.canvasBufferPosition.y = e.pageY;
            //记录当前的位置
            this.canvasThisDownPosition.x = this.requestData.canvasThisPosition.x;
            this.canvasThisDownPosition.y = this.requestData.canvasThisPosition.y;

            //判断当前选择的内容是否在体制内如果没有则清空选择的内容
            let isDownObjct = false;

            for (let i = 0; i < this.mouse_selectComponentIdS.length; i++) 
            {
                let selectId = this.mouse_selectComponentIdS[i];

                let {dom}  = util_parseDomPath({
                    path:e.path,
                    el:".movetrue"
                });
                if(selectId == dom.id)
                {
                    //判断当前是否选择到的内容
                    // console.log(dom.id);
                    isDownObjct = true;
                }
               

            }
            //当按下ctrl则通过任何内容
            if(this.mouse_selectKeyDown_ctrl)
            {
                isDownObjct = true;
            }



            //判断当前选中的内容是否在物体上的
            if(!isDownObjct) 
            {
                this.mouse_selectComponentIdS = [];
            }


            //记录当前选中的位置
            this.mouse_selectBufferPosition = [];
            for (let i = 0; i < this.mouse_selectComponentIdS.length; i++) 
            {
                let selectId = this.mouse_selectComponentIdS[i];
                if (selectId != undefined) 
                {
                    let {x,y} = this.requestData[this.requestData.modelType][selectId].data.position;
                    this.mouse_selectBufferPosition.push({
                        x:x,
                        y:y,
                    });
                }
            }
           
        },
        /**
         * window 事件当前的鼠标移动时的动作
         * @param {事件} e 
         */
        eventWin_mouseMove: function (e) 
        {
            //将当前的鼠标path传入到公共变量里面去
            this.mouse_movePath = e.path;
            //获取滑动的xy轴
            let {pageX , pageY} = e;
            //计算差值
            let differenceX = pageX - this.canvasBufferPosition.x;
            let differenceY = pageY - this.canvasBufferPosition.y;
            /**
             * 当前鼠标指针按下 和空格按下才可执行当前的移动中的内容
             */
            if(this.mouse_isDown && this.mouse_moveBody){
                //记录最后的按下空格时的位置加上当前移动的差值就是所移动的位置
                //有个问题就是缩小和放大时位置不一样为了解决这样问题修改计算差值
                let scale = 1/(this.requestData.mediaSize.data / 100)   ;
                // console.log(scale);

                this.requestData.canvasThisPosition.x = this.canvasThisDownPosition.x  +(differenceX*scale) ;
                this.requestData.canvasThisPosition.y = this.canvasThisDownPosition.y +(differenceY*scale);

                // console.log("------------------------滑过内容-",e.path);




            }


            /**
             * 当前鼠标按下执行
             */
            else if(this.mouse_isDown)
            {
                let scale = 1/(this.requestData.mediaSize.data / 100)   ;


                for (let i = 0; i < this.mouse_selectComponentIdS.length; i++) {
                    let selectId = this.mouse_selectComponentIdS[i];
                    let itemData = null;
                    try{
                        itemData    = this.requestData[this.requestData.modelType][selectId].data;
                    }catch(e)
                    {
                        //如果当前数据是错误的或者找不到则跳过当前循环
                        continue;
                    }

                    itemData.position.x = this.mouse_selectBufferPosition[i].x  +(differenceX*scale) ;
                    itemData.position.y =  this.mouse_selectBufferPosition[i].y  +(differenceY*scale) ;
                    // this.mouse_selectBufferPosition.push({
                    //     x:x,
                    //     y:y,
                    // });
                }
            } 
            
            //执行move的方法列表
            // this.mouse_move_funs
            

        },
        /**
         * window 事件当前的鼠标抬起的动作
         * @param {事件} e 
         */
        eventWin_mouseUp: function (e) 
        {
            
            //当前鼠标按下时不可选择内容
            this.$el.style.userSelect = "all";
            this.mouse_isDown = false;
        },
        /**
         * body事件当前的点击的内容是否选中
         * @param {*} e 
         */
        eventBody_click:function(e,mouseDown)
        {
            // console.log("dsfsdfsdfsdfsdfsf");
            //获取当前可移动的模块
            let {dom}  = util_parseDomPath({
                path:e.path,
                el:".movetrue"
            });

            //判断如果点击为空的话清空内容并且不执行
            if(dom == "")
            {
                this.mouse_selectComponentIdS.splice(0,this.mouse_selectComponentIdS.length);
                return;
            }


            //判断当前是否是手型如果是手型则不知行
            if(!this.mouse_moveBody){
                //判断是否按着ctrl键
                if(this.mouse_selectKeyDown_ctrl)
                {
                    let repeat = false;
                    //判断不重复
                    for (let i = 0; i < this.mouse_selectComponentIdS.length; i++) {
                        const item = this.mouse_selectComponentIdS[i];

                        if(item == dom.id)
                        {
                            //取消选择



                            
                            this.mouse_selectComponentIdS.splice(i,1);

                            repeat = true;
                            break;
                        }
                        
                    }
                    if(!repeat)  //不重复则执行
                    { 
                        // if(dom.id != undefined)
                        // {
                            this.mouse_selectComponentIdS.push(dom.id);
                        // }

                    }
                    
                }else
                {
                    //什么请情况才能阻止当前执行?物体移动后阻止当前?
                    if(mouseDown == undefined){
                        this.mouse_selectComponentIdS = [dom.id];
                    }
                    
                    

                    
                    
                }

            }
        },
        /**
         * window 事件当前的键盘按下的事件
         * @param {事件} e 
         */
        eventWin_keyDown: function (e)
        {
            let { code, key } = e;
            console.log("简单逻辑键盘编码:" + code + ";键盘字符:" + key);
            if (code == "Space") 
            {
                this.fun_dom_isBodyMouse(true); //当前键盘按钮按下
            } 
            else if(code == "ControlLeft")
            {
                this.mouse_selectKeyDown_ctrl = true;
            }

        },
        /**
         * window 的键盘抬起的事件
         * @param {事件} e 
         */
        evnetWin_keyUp: function (e)
        {
            let { code, key } = e;
            if (code == "Space")
            {
                this.fun_dom_isBodyMouse(false); //当前键盘按钮抬起
            } 
            else if(code == "ControlLeft")
            {

                this.mouse_selectKeyDown_ctrl = false;
            }
        },
        /**
         * window  的滚轮事件
         * @param {} e 
         */
        eventWin_mouseRoll:function(e){


            let isBodyData = util_parseDomPath({
                path: this.mouse_movePath,
                el: "#body-object",
            });
            console.log("滚轮事件--------------------",0 - e.deltaY/100 );
            if(isBodyData.code == 0)
            {
                let scrollData = (0 - e.deltaY/100);

                // 判断当前空格是否放下
                if(this.mouse_moveBody)
                {
                    //缩放屏幕
                    let size = this.requestData.mediaSize.data +scrollData*2;
                    if(size >= 10 && size <= 200){
                        this.requestData.mediaSize.data = size; 
                    }

                }else
                {
                    //滚动屏幕
                     this.requestData.canvasThisPosition.y =   this.requestData.canvasThisPosition.y+ (scrollData*100);
                }


                

            }



        },
        eventWin_widowSize:function(e)
        {
            this.window.w = window.innerWidth;
            this.window.h = window.innerHeight;
        },


        /**----------------------------------------------------------------------------
         * window当前框的事件方法封装内容
         */
        fun_test: function ()
        {

        },

        /**
         * 类型: 方法
         * 功能: 操作dom
         * 被执行: 键盘空格按下或者抬起
         * 判断当前鼠标是否该手型
         */
        fun_dom_isBodyMouse: function (isDown) 
        {
            //键盘按下      
            if (isDown) 
            { 
                //阻止重复内容
                if(fun_dom_isBodyMouse != undefined )return;
                fun_dom_isBodyMouse = 1;

                //判断当前是否是在body里面执行的
                let isBodyData = util_parseDomPath({
                    path: this.mouse_movePath,
                    el: "#body",
                });
                // 判断当前是否有选中的内容
                // console.log(isBodyData);
                if(isBodyData.data)
                {
                    this.$el.style.cursor = "grab";
                    this.$el.style.userSelect = "none";
                    this.mouse_moveBody = true;
                }



            } 
            //键盘抬起
            else 
            {  
                //解除阻止重复
                fun_dom_isBodyMouse = undefined; 

                console.log("键盘台起");
                this.$el.style.cursor = "auto";
                this.$el.style.userSelect = "all";
                /**
                 * 是否拖拉的空格清空
                 */
                this.mouse_moveBody = false;
                /**
                 * 鼠标指针按键抬起
                 */
                this.mouse_isDown = false;
            }


        },

        //获取网络上的数据---------------------------------------------------
        fun_data_requestData:function(code)
        {
            console.log("通过c ode请求数据   请求的code",code);
            // 判断当前是否请求什么库的内容
            

            //如果执行的方法为空则使用头部的标签
            if(code != undefined)
            {
                //使用本地标签
                main.requestData.projectCode = code;
               
            }else
            {
                main.requestData.projectCode = getUrlParams("uuid");
            }




            


            console.log(getUrlParams("uuid"));


            axios({
                url:REQUEST_DATA_URL,
                params:{
                    "code": main.requestData.projectCode
                },
                method:REQUEST_DATA_METHOD
            }).then(res=>{
                console.log(JSON.parse(JSON.stringify(res)));
                console.log(res);
                let {data} = res;
                
                if(data.code == 0)
                {

                    //判断当前数据是否为空或者找不到
                    if(data.data != null && data.data != undefined)
                    {

                        let newData = {...this.requestData,...data.data};

                        this.$set(
                            this,
                            "requestData",
                            newData,
                        );
                    }else{
                        let template = {
                            mediaSize:{data:100},              //当前屏幕缩放
                            canvasThisPosition:{
                                x:0,
                                y:0
                            },
                            projectName:"项目名称",         //当前的项目名称
                            projectCode:main.requestData.projectCode, //当前项目的数据库编码
                            modelType:'model_server',     //server端  和  app端
                            model_server:{},
                            model_app:{},
                        };
                        

                        this.$set(
                            this,
                            "requestData",
                            template,
                        );

                    }
                    console.log("------------------------------------");

                     
                    //初始化项目名称
                    this.fun_data_init_header();
                    // 网络请求完毕执行内容
                    this.fun_data_ifDataInit();
                    //同步到控制栏
                    this.fun_toMediaSize();
                    //初始化线段
                    this.fun_component_updateLink();
                }
                
            }).catch(err=>{

            })



        },
        /**
         * 保存当前的数据到服务器里面
         */
        fun_data_saveData:function()
        {
            let saveData = JSON.stringify(this.requestData);
            console.log(saveData);


            axios({
                url:SAVE_DATA_URL,
                params:{
                    "code": main.requestData.projectCode,
                    "projectData":saveData,
                },
                method:SAVE_DATA_METHOD
            }).then(res=>{
                alert("保存成功");
                
            }).catch(err=>{
                alert("保存失败");
            })

        },
        //当前数据初始化时更新数据
        fun_data_ifDataInit:function(){
            //判断当前数据是否为空
            //当前某个对象为空的话则添加主要函数
            if( Object.getOwnPropertyNames(this.requestData.model_server).length-1 == 0)
            {
                this.$set(
                    this.requestData.model_server, 
                    uuid(), 
                    this.fun_data_getTemplate(
                        "main_group_home",
                        {
                            type:"服务端",
                            projectName:this.requestData.projectName+"_server",
                        }
                    )
                );
               
                
            }

            if ( Object.getOwnPropertyNames(this.requestData.model_app).length-1 == 0) 
            {
                // this.requestData.model_app[uuid()] = this.fun_data_getTemplate("canvas_svg_table");
                this.$set(
                    this.requestData.model_app, 
                    uuid(), 
                    this.fun_data_getTemplate(
                        "main_group_home",
                        {
                            type:"App端",
                            projectName:this.requestData.projectName+"_app",
                        }
                    )
                );
            }
            
            

        },
        /**
         * 初始化头部数据
         */
        fun_data_init_header:function()
        {
            header.data_setTitleName(this.requestData.projectName);
            //插入当前的模式
            header.data_setModelType(this.requestData.modelType);

        },

        /**
         * 当前是获取模板的内容用于模板的copy
         * @param {*} componentName 
         * @returns 
         */
        fun_data_getTemplate:function(componentName,data){
            let template = {
                component:componentName,
                data:data,

            };
            return template;
        },
        /**
         *当前的页面大小内容传入到控制组里面
         */
        fun_toMediaSize:function(){
            //将当前的屏幕大小的引用传递给控制器
            controller.data_setMediaSize(this.requestData.mediaSize);
        },
        /**
         * 通过名称添加子节点 创建node
         */
        fun_component_addChildren:function(parentId,childrenName,thisId)
        {
            // console.log("--------------------");
            /**
             * 创建uuid的名称
             */
            let uuids = thisId != undefined?thisId:uuid();
            /**
             * 获取父节点的数据
             */
            let parentData = this.requestData[this.requestData.modelType][parentId].data;

            /**
             * 插入数据位置
             */
            let position = {
                x:parentData.position.x + 400,
                y:parentData.position.y ,
            }
            if(childrenName == "space_component_users")
            {
                position.x = parentData.position.x - 400 ;
            }
            /**
             * 判断当前父节点是否有子节点
             */
            if(parentData.childrenListId.length >= 1)
            {
                //同类的内容创建的 编码
                let className = null;

                /**
                 * 遍历当前的key值
                 */
                for (const key in parentData.childrenListId) {
                    
                    /**
                     * 获取当前的key类型是什么
                     */
                    let id = parentData.childrenListId[key];
                    let thisComponentName = this.requestData[this.requestData.modelType][id].component;
                    /**
                     * 如果当前的组件名称  和创建的组件名称相同则执行
                     */
                    if(thisComponentName == childrenName)
                    {   
                        //赋予类中的最后的一个编码的名称
                        className = id;
                    }
                }
                /**
                 * 当前有同类
                 */
                if(className != null)
                {   
                    try{
                         // debugger
                        //同类的 编码地址
                        let classNameData =  this.requestData[this.requestData.modelType][className].data;

                        position.y = classNameData.innerSize.height + classNameData.position.y + 10;
                        position.x = classNameData.position.x ;

                    }catch(e)
                    {
                        console.log("当前内容错误",e);
                    }
                   

                    


                }
                /**
                 * 没有同类则取默认值
                 */
                // else if(childrenName == "space_component_users")
                // {
                //     position.x = parentData.position.x - 400 ;
                // }




            }else
            /**
             * 当前父节点没有子节点就默认创建内容
             */
            {


                position.y  = parentData.position.y + parentData.innerSize.height /2;

            }
            //插入数据
            this.$set(
                this.requestData[this.requestData.modelType], 
                uuids, 
                //创建模板
                this.fun_data_getTemplate(
                    childrenName,
                    {
                        parentId:parentId,
                        position:position,
                    }
                )
            );
            // //添加完毕同步到父级的children列表里面
            // parentData.childrenListId.push(uuids);
        },
        /**
         * 
         * @param {删除指定的内容} thisId 
         */
        fun_component_remChildren:function(thisId){
            console.log("删除当前的内容");
            // mouse_selectComponentIdS

            //
            // delete [];
            console.log(this);

            //清空string
            
            //刷新线数据
            main.fun_component_updateLink(()=>{
                /**
                 * 删除父级的当前children
                 */
                if(thisId == undefined)
                {   
                     //获取父级
                    let parentObject = this.requestData[this.requestData.modelType][ properties.thisObject.data.parentId];
                    if(parentObject != undefined)
                    {
                        //获取当前数据的父级data
                        let parentData = parentObject.data   ;
                        //删除父级的当前children编码
                        for (const i in parentData.childrenListId) {
                            if(parentData.childrenListId[i] == properties.thisObjectUUid)
                            {
                                parentData.childrenListId.splice(i,1);
                            }
                        }
                    }
                    //删除当前的模块
                    this.$delete(this.requestData[this.requestData.modelType],properties.thisObjectUUid);
                }else
                {
                    //删除当前的模块
                    this.$delete(this.requestData[this.requestData.modelType],thisId);
                }
               
               
            
            });
            //删除元素
            
            //刷新string
            // main.fun_component_updateLink();
        },
        
        /**
         *   创建line link  更新线段
         */
        fun_component_updateLink:function(functions)
        {


            let returnData = [];

          


            if(functions != undefined)
            {
                functions();
            }


             // return;
            //当前模式的对象列表
            let thisModel = this.requestData[this.requestData.modelType];
            
            /**
             * 遍历当前的对象
             */
            for (const key in thisModel) {
                /**
                 * 当前的对象的子集
                 */
                let thidChildrenIdS = thisModel[key].data.childrenListId;
                if(thidChildrenIdS != undefined){
                    for (let i = 0; i < thidChildrenIdS.length; i++) {
                        let childrenId = thidChildrenIdS[i];
                        let linkObject = {
                            parentId:key,
                            childrenId:childrenId,
                        };
                        // console.log(linkObject);

                        returnData.push(linkObject);
                        
                    }
                }   
                    
                // console.log("sdfsdf",key);
                
            }
            this.stringList = returnData;
        },
        /**
         * 让所有的按钮失去焦点时执行失去焦点事件
         */
        fun_mouseBlurs:function(){
            let all = document.getElementsByTagName("button");

            for (let i = 0; i < all.length; i++) {
                let element = all[i];
                element.index = i;
                element.onmouseout = function(){
                    all[this.index].blur();
                }
            }
        }

    },
    created() 
    {
        // console.log(this.test);

        //获取当前的dom插入数据
        var body = document.getElementsByTagName("body")[0];

        // body.setAttribute("");
        window.onmousedown = this.eventWin_mouseDown;
        window.onmousemove = this.eventWin_mouseMove;
        window.onmouseup = this.eventWin_mouseUp;

        window.onkeydown = this.eventWin_keyDown;
        window.onkeyup = this.evnetWin_keyUp;
        window.onresize = this.eventWin_widowSize;
        window.onmousewheel = this.eventWin_mouseRoll;
        this.eventWin_widowSize();


        setTimeout(()=>{
            
            //注册body的事件
            // console.dir(this.$el);
            this.$el.onclick = this.eventBody_click;
            this.fun_data_requestData();
        },1000);

        setInterval(()=>{
            this.fun_mouseBlurs();
        },1000);
        this.fun_mouseBlurs();
        

        
    }


});
